package com.nbicc.dp.wsgateway.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbicc.db.modular.dp.panel.model.Panel;
import com.nbicc.dp.wsgateway.common.WsRequest;
import com.nbicc.dp.wsgateway.service.PanelOnOffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @Author: lilingyan
 */
@Slf4j
@Component
public class PanelHandler extends TextWebSocketHandler {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private WsRequestMappingHandler wsRequestMappingHandler;
    @Autowired
    private PanelOnOffService panelOnOffService;

    public PanelHandler() {
    }

    /**
     * 在WebSocket协商成功后，WebSocket连接被打开并准备好使用。
     * 连接建立成功之后，记录用户的连接标识，便于后面发信息
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        session.sendMessage(new TextMessage("连接成功  我是服务器"));
        panelOnOffService.comeOnline(panelOnOffService.getPanelIdByUri(session.getUri()), session);
    }

    /**
     * 当一个新的WebSocket消息到达时调用。
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info("websocet接收到消息:"+message);
        WsRequest wsRequest = objectMapper.readValue(message.getPayload(), WsRequest.class);
        wsRequestMappingHandler.executeByTag(session , wsRequest);
    }

    /**
     * 处理来自底层WebSocket消息传输的错误。
     * 连接出错处理，主要是关闭出错会话的连接，和删除在Map集合中的记录
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error(exception.toString());
        super.handleTransportError(session, exception);
        if(session.isOpen()){
            session.close();
        }
        panelOnOffService.offline(session);
    }

    /**
     * 在网络套接字连接关闭后或在传输错误发生后调用。
     * 连接已关闭，移除在Map集合中的记录。
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        panelOnOffService.offline(session);
    }
}
